//
//  MyDatePickerView.m
//  datePickerView
//
//  Created by lianchuang on 14-11-19.
//  Copyright (c) 2014年 lianchuang. All rights reserved.
//

#import "MyDatePickerView.h"

#define YEAR_CIRCULATE_TIMES 50
#define YEAR_COUNT 201

#define MONTH_CIRCULATE_TIMES 1000
#define MONTH_COUNT 12

#define DAY_CIRCULATE_TIMES 400

#define HOUR_CIRCULATE_TIMES 500
#define HOUR_COUNT 24

#define MINUTE_CIRCULATE_TIMES 200
#define MINUTE_COUNT 60

@implementation MyDatePickerView


- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        
        [self makePickerView];
        
    }
    return self;
}

-(void)makePickerView
{
    self.backgroundColor = [UIColor whiteColor];
    
    self.cancleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.cancleButton.frame = CGRectMake(15, 10, 50, 30);
    [self.cancleButton setTitle:@"取消" forState:UIControlStateNormal];
    self.cancleButton.titleLabel.font = [UIFont systemFontOfSize:15];

    [self.cancleButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self addSubview:self.cancleButton];
    //
    self.sureButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.sureButton.frame = CGRectMake(self.frame.size.width-65, 10, 50, 30);
    [self.sureButton setTitle:@"确定" forState:UIControlStateNormal];
    [self.sureButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self addSubview:self.sureButton];
    self.sureButton.titleLabel.font = [UIFont systemFontOfSize:15];
    //
    self.datePickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 40, self.width, self.height-40)];
    self.datePickerView.delegate = self;
    self.datePickerView.dataSource = self;
    [self addSubview:self.datePickerView];
    

    //
    [self getNowDate];
}

-(void)getNowDate
{
    //初始化年月日
    NSDate *nowDate = nil;
    if (self.defaultDate) {
        nowDate = self.defaultDate;
        
    } else {
        nowDate = [NSDate date];
        
    }
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd-HH-mm"];
    NSString *dateStr = [formatter stringFromDate:nowDate];
    NSArray *dateArray = [dateStr componentsSeparatedByString:@"-"];
    _year = [dateArray[0] intValue];
    self.nowYear = dateArray[0];
    _month = [dateArray[1] intValue];
    self.nowMonth = dateArray[1];
    _day = [dateArray[2] intValue];
    self.nowDay = dateArray[2];
    _hour = [dateArray[3] intValue];
    _minute = [dateArray[4] intValue];
    //指向现在的时间
    //您指向1990
    [self.datePickerView selectRow:[self calculateMiddleIndexWithFirstIndex:1990 - 1900 circulateTimes:YEAR_CIRCULATE_TIMES elementCount:[self getYEAR_COUNT]] inComponent:0 animated:NO];
    _year = 1990;
    [self.datePickerView selectRow:[self calculateMiddleIndexWithFirstIndex:self.month - 1 circulateTimes:MONTH_CIRCULATE_TIMES elementCount:MONTH_COUNT] inComponent:1 animated:NO];
    [self.datePickerView selectRow:[self calculateMiddleIndexWithFirstIndex:self.day - 1 circulateTimes:DAY_CIRCULATE_TIMES elementCount:[self calculateForDays]] inComponent:2 animated:NO];
 

}
/**
 *  如果选择的日期超过当前日期的话就让他自动指向现在的时间现在的年、月、日
 */
-(void)scrollToNowYearMonthDay
{
    [self.datePickerView selectRow:[self calculateMiddleIndexWithFirstIndex:[self.nowYear integerValue] - 1900 circulateTimes:YEAR_CIRCULATE_TIMES elementCount:[self getYEAR_COUNT]] inComponent:0 animated:NO];
    
    _year = [self.nowYear integerValue];
    [self.datePickerView selectRow:[self calculateMiddleIndexWithFirstIndex:[self.nowMonth intValue] - 1 circulateTimes:MONTH_CIRCULATE_TIMES elementCount:MONTH_COUNT] inComponent:1 animated:NO];
    _month = [self.nowMonth integerValue];
    [self.datePickerView selectRow:[self calculateMiddleIndexWithFirstIndex:[self.nowDay intValue]- 1 circulateTimes:DAY_CIRCULATE_TIMES elementCount:[self calculateForDays]] inComponent:2 animated:NO];
    _day = [self.nowDay integerValue];
}

-(NSInteger)getYEAR_COUNT{
    
    NSDate *nowDATE= [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd-HH-mm"];
    NSString *dateStr = [formatter stringFromDate:nowDATE];
    NSArray *dateArray = [dateStr componentsSeparatedByString:@"-"];
    NSInteger nowyear = [dateArray[0] intValue];
    
    return  nowyear - 1900+1;
}


- (NSInteger)calculateMiddleIndexWithFirstIndex:(NSInteger)firstIndex circulateTimes:(NSInteger)times elementCount:(NSInteger)count
{
    if (times % 2 != 0) {
        times--;
        
    }
    NSInteger index = firstIndex + times / 2 * count;
    return index;
}
- (NSString *)getDateString
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
        [formatter setDateFormat:PLAIN_DATE_FORMAT];
    
    NSDate *date = [self getDate];
    
    return [formatter stringFromDate:date];
    
}
- (NSDate *)getDate
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd-HH-mm"];
    NSDate *date = [formatter dateFromString:[NSString stringWithFormat:@"%ld-%ld-%ld-%ld-%ld", self.year, self.month, self.day, self.hour, self.minute]];
    return date;
}
//计算选中的月份有多少天
- (NSInteger)calculateForDays
{
    NSCalendar *calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM"];
    NSDate *date = [formatter dateFromString:[NSString stringWithFormat:@"%ld-%ld", self.year, self.month]];
    NSRange dayRange = [calendar rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:date];
    return dayRange.length;
    
}


#pragma mark - UIPickerViewDelegate and DataSource -

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    if (pickerView == self.datePickerView) {
        return 3;

    }else
    {
        return 0;
    }
    
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    switch (component) {
        case 0:
            return YEAR_CIRCULATE_TIMES * [self getYEAR_COUNT];
            break;
            
        case 1:
            return MONTH_CIRCULATE_TIMES * MONTH_COUNT;
            break;
            
        case 2:
            return [self calculateForDays] * DAY_CIRCULATE_TIMES;
            break;
            
        case 3:
            return HOUR_CIRCULATE_TIMES * HOUR_COUNT;
            break;
            
        case 4:
            return MINUTE_CIRCULATE_TIMES * MINUTE_COUNT;
            break;
            
        default:
            return 0;
            break;
    }
    
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    if (pickerView == self.datePickerView) {
        return 90.0;
    }else
    {
        return 0;
    }
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    if (pickerView == self.datePickerView) {

        UILabel *label = nil;
        label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 90, 20)];
        label.font = [UIFont boldSystemFontOfSize:14.f];
        label.backgroundColor = [UIColor clearColor];
        label.textAlignment = NSTextAlignmentCenter;
        switch (component) {
            case 0:
                label.text = [NSString stringWithFormat:@"%ld年", row % [self getYEAR_COUNT] + 1900];
                break;
                
            case 1:
                label.text = [NSString stringWithFormat:@"%.2ld月", row % MONTH_COUNT + 1];
                break;
                
            case 2:
                label.text = [NSString stringWithFormat:@"%.2ld日", row % [self calculateForDays] + 1];
                break;
                
            case 3:
                label.text = [NSString stringWithFormat:@"%.2ld时", row % HOUR_COUNT];
                break;
                
            case 4:
                label.text = [NSString stringWithFormat:@"%.2ld分", row % MINUTE_COUNT];
                break;
                
            default:
                return nil;
                break;
        }
        return label;
        
        
    }else
    {
        return nil;
    }
    
    
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (pickerView == self.datePickerView) {
        
        if (component == 0) {
            
            _year = row % [self getYEAR_COUNT] + 1900;
            
            //更新day
            [pickerView reloadComponent:2];
            
            if ([self calculateForDays] < self.day) {
                _day = (NSInteger)[self calculateForDays];
                
            }
            
            [pickerView selectRow:[self calculateMiddleIndexWithFirstIndex:self.day - 1 circulateTimes:DAY_CIRCULATE_TIMES elementCount:[self calculateForDays]] inComponent:2 animated:NO];
            
            _day = (NSInteger)[pickerView selectedRowInComponent:2] % [self calculateForDays] + 1;
            //复原到中间位置
            [pickerView selectRow:[self calculateMiddleIndexWithFirstIndex:self.year - 1900 circulateTimes:YEAR_CIRCULATE_TIMES elementCount:[self getYEAR_COUNT]] inComponent:0 animated:NO];
            
        }
        if (component == 1){
        
            _month = row % MONTH_COUNT + 1;
            
            //更新day
            [pickerView reloadComponent:2];
            
            if ([self calculateForDays] < self.day) {
                _day = (NSInteger)[self calculateForDays];
                
            }
            
            [pickerView selectRow:[self calculateMiddleIndexWithFirstIndex:self.day - 1 circulateTimes:DAY_CIRCULATE_TIMES elementCount:[self calculateForDays]] inComponent:2 animated:NO];
            
            _day = (NSInteger)[pickerView selectedRowInComponent:2] % [self calculateForDays] + 1;
            
            //复原到中间位置
            [pickerView selectRow:[self calculateMiddleIndexWithFirstIndex:self.month - 1 circulateTimes:MONTH_CIRCULATE_TIMES elementCount:MONTH_COUNT] inComponent:1 animated:NO];
        
        }
        if (component == 2) {
            _day = (NSInteger)row % [self calculateForDays] + 1;
            
            //复原到中间位置
            [pickerView selectRow:[self calculateMiddleIndexWithFirstIndex:self.day - 1 circulateTimes:DAY_CIRCULATE_TIMES elementCount:[self calculateForDays]] inComponent:2 animated:NO];
        }
        if (component == 3) {
            _hour = row % HOUR_COUNT;
            
            [pickerView selectRow:[self calculateMiddleIndexWithFirstIndex:self.hour circulateTimes:HOUR_CIRCULATE_TIMES elementCount:HOUR_COUNT] inComponent:3 animated:NO];
        }
        if (component == 4) {
            _minute = row % MINUTE_COUNT;
            
            [pickerView selectRow:[self calculateMiddleIndexWithFirstIndex:self.minute circulateTimes:MINUTE_CIRCULATE_TIMES elementCount:MINUTE_COUNT] inComponent:4 animated:NO];
        }
        
        
        if (_year > [self.nowYear integerValue] || (_year == [self.nowYear integerValue] && _month > [self.nowMonth integerValue]) ||(_year == [self.nowYear integerValue] && _month == [self.nowMonth integerValue] && _day > [self.nowDay integerValue])) {
            [self scrollToNowYearMonthDay];
        }
    }
}


@end
